package com.coder4j.platform.config;

import com.coder4j.platform.cache.AuthCache;
import com.coder4j.starter.web.util.AuthUtils;
import com.coder4j.starter.web.jwt.AuthVO;
import com.coder4j.starter.web.jwt.TokenUtils;
import com.coder4j.platform.service.AuthApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限拦截器
 * @author keller
 * @date 2024-5-16 14:29:52
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private AuthApiService authApiService;

    @Resource
    private AuthCache authCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("----------AuthInterceptor--{}",request.getRequestURI());
        // 检查是否是WebSocket Upgrade请求
        if ("WebSocket".equalsIgnoreCase(request.getHeader("Upgrade"))) {
            // 如果是WebSocket Upgrade请求，则直接放行
            return true;
        }
        log.info("----------AuthInterceptor running--{}",request.getRequestURI());

        AuthVO authVO = AuthUtils.getAuthVO();
        if(authVO == null){
            Long userId = TokenUtils.getUserId(request);
            if(userId != null){
                //ThreadLocal 存入用户角色
                AuthUtils.setAuthVO(authCache.getAuthUserCache(userId));
            }
            authVO = AuthUtils.getAuthVO();
        }

        if(authVO != null && authApiService.checkApiRights(authVO.getRoleId(),request)){
            return true;
        }
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }

}
